package com.sk.skplanet.commute.actions;

import java.util.List;

import android.os.AsyncTask;

import com.sk.skplanet.commute.actions.APIRequestBus2.RequestMethod;
import com.sk.skplanet.commute.controllers.SeoulBusApiController;
import com.sk.skplanet.commute.parser.GetRouteByStationParser;
import com.sk.skplanet.commute.parser.GetStationByRouteParser;
import com.sk.skplanet.commute.parser.GetStationByUidParser;
import com.sk.skplanet.commute.parser.SeoulBusAPIParser;

public class APIRequestBus2 extends AsyncTask<RequestMethod, Integer, String> {
	private static RequestMethod sMethod;
	private static String sArsId;
	private static String sCacheResult;
	OnBusRequestCompleted mListener;
	private String arsId;
	private int requestCode;
	public enum RequestMethod {
		API_GETSTATIONBYROUTELIST,
		API_GETROUTEBYSTATION,
		API_GETSTATIONBYUID;
	}
	
	private RequestMethod currentMethod; 
	
	public APIRequestBus2(int requestCode, String id, OnBusRequestCompleted i) {
		this.arsId = id;
		this.mListener = i;
		this.requestCode = requestCode;
		sMethod = null;
		sArsId = null;
		sCacheResult = null;
	}
	
	public static void completeAPIRequest() {
		sMethod = null;
		sArsId = null;
		sCacheResult = null;
	}
	
	@Override
	protected String doInBackground(RequestMethod... arg0) {
		currentMethod = arg0[0];
		
		if(sMethod != null && sMethod == currentMethod && sArsId != null && arsId.equals(sArsId)) {
			return sCacheResult;
		}
		
		String result = "";
		SeoulBusApiController sbac = new SeoulBusApiController("");
		
		try {
			switch(currentMethod) {
				case API_GETSTATIONBYROUTELIST :
					result = sbac.getStationsByRouteList(arsId);
					break;
				case API_GETROUTEBYSTATION :
					result = sbac.getRouteByStation(arsId);
					break;
				case API_GETSTATIONBYUID :
					result = sbac.getStationByUid(arsId);
					break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		// 중복요청 막기위한 임시값 저장.
		sCacheResult = result;
		sArsId = arsId;
		sMethod = currentMethod;
		return result;
	}

	@Override
	protected void onPostExecute(String result) {
		super.onPostExecute(result);
		
		if(result == null || "".equals(result)) {
			if(mListener != null)
				mListener.onBusRequestCompleted(requestCode, null);
			return;
		}
		
		// Parsing start
		SeoulBusAPIParser parser = null;
		
		switch(currentMethod) {
			case API_GETSTATIONBYROUTELIST :
				parser = new GetStationByRouteParser(result);
				break;
			case API_GETROUTEBYSTATION :
				parser = new GetRouteByStationParser(result);
				break;
			case API_GETSTATIONBYUID :
				parser = new GetStationByUidParser(result);
				break;
		}
		
		if(mListener != null && parser != null)
			mListener.onBusRequestCompleted(requestCode, parser.parse());
	}

	public interface OnBusRequestCompleted {
		public void onBusRequestCompleted(int requestCode, List<?> data);
	}
}
